import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/string_util.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_assess_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_res_goods_detail_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_team_member_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/emergency/resource/detail/model.dart';

typedef _Info = (
  String name,
  String type,
  String amount,
  String usage,
  String requirement,
  /// 图片链接
  List<String> urls,
);

/// 应急资源详情
class EmergencyResourceDetailController extends GetxController {
  int _tabIdx = 0;
  int get tabIdx => _tabIdx;
  set tabIdx(int value) {
    _tabIdx = value;
    update();
  }

  final args = (Get.arguments as Map?) ?? {};

  late final type = args['type'] as EmergencyResourceDetailPageType?;

  late final data = args['data'];

  late final tabs = type?.tabs ?? const [];

  Tab get tab => tabs[tabIdx];

  /// 评估记录
  List<EmergencyAssessEntity> assessList = [];

  /// 加载评估记录
  Future<void> loadAssess() async {
    late final String url;
    late final Map<String, dynamic> args;
    switch (type) {
      case EmergencyResourceDetailPageType.expert:
        url = '${Interface.mainBaseUrl}/emergency//emergencyExperts/getEmergencyExpertsRecord';
        args = {'emergencyExpertId': data.id};
        break;
      case EmergencyResourceDetailPageType.goods:
        url = '${Interface.mainBaseUrl}/emergency//EmergencySupplies/getMaterialPointRecord';
        args = {'materialPointId': data.id};
        break;
      case EmergencyResourceDetailPageType.team:
        url = '${Interface.mainBaseUrl}/emergency//emergencyTeam/getEmergencyTeamRecord';
        args = {'emergencyTeamId': data.id};
        break;
      case EmergencyResourceDetailPageType.target:
        url = '${Interface.mainBaseUrl}/emergency//sensitiveTargets/getSensitiveTargetsRecord';
        args = {'sensitiveTargetsId': data.id};
        break;
      case EmergencyResourceDetailPageType.nearby:
        url = '${Interface.mainBaseUrl}/emergency//surrounding/getSurroundingResourcesRecord';
        args = {'surroundingResourcesId': data.id};
        break;
      default:
        return;
    }
    final resp = await HttpUtil()
        .generateGetRequest<List<EmergencyAssessEntity>>(
          url,
          queryParameters: args,
        )
        .execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        assessList.addAll(data);
        update();
      }
    });
  }

  /// 是否显示评估
  bool get displayInfo {
    switch (type) {
      case EmergencyResourceDetailPageType.goods || EmergencyResourceDetailPageType.team:
        return true;
      default:
        return false;
    }
  }

  final infos = <_Info>[];

  /// 获取详情信息
  Future<List<_Info>?> get _infos async {
    switch (type) {
      case EmergencyResourceDetailPageType.goods:
        return await _goodsInfo;
      case EmergencyResourceDetailPageType.team:
        return await _teamInfo;
      default:
        return null;
    }
  }

  /// 物资详情
  Future<List<_Info>?> get _goodsInfo async {
    final resp = await HttpUtil().generateGetRequest<List<EmergencyResGoodsDetailEntity>>(
      '${Interface.mainBaseUrl}/emergency//EmergencySupplies/getMaterialPointDetailsList',
      queryParameters: {'materialPointId': data.id},
    ).execute();
    final res = resp.data;
    if (res == null) return null;
    return res
        .map((e) => (
              e.materialName ?? '',
              e.materialClassificationName ?? '',
              e.quantity?.toString() ?? '',
              e.purpose ?? '',
              e.transportationAndStorageRequirements ?? '',
              e.materialPhotos?.split(',') ?? [],
            ))
        .toList();
  }

  /// 队伍详情
  Future<List<_Info>?> get _teamInfo async {
    final data2 = StringUtil.fromBackendIds(data.emergencyPointIds as String? ?? '[]');
    final resp = await HttpUtil()
        .generatePostRequest<List<EmergencyResGoodsDetailEntity>>(
          '${Interface.mainBaseUrl}/emergency//emergencyTeam/getMaterialPointDetailsByIds',
          data: data2,
        )
        .execute();
    final res = resp.data;
    if (res == null) return null;
    return res
        .map((e) => (
              e.materialName ?? '',
              e.materialClassificationName ?? '',
              e.quantity?.toString() ?? '',
              e.purpose ?? '',
              e.transportationAndStorageRequirements ?? '',
              e.materialPhotos?.split(',') ?? [],
            ))
        .toList();
  }

  /// 队伍成员
  final members = <EmergencyTeamMemberEntity>[];
  Future<void> loadMemebers() async {
    final resp = await HttpUtil().generateGetRequest<List<EmergencyTeamMemberEntity>>(
      '${Interface.mainBaseUrl}/emergency//emergencyTeam/getTeamMemberList',
      queryParameters: {'teamId': data.id},
    ).execute();
    final res = resp.data;
    if (res == null) return;
    members.addAll(res);
    update();
  }

  @override
  Future<void> onInit() async {
    super.onInit();
    loadMemebers();
    loadAssess();
    infos.addAll(await _infos ?? []);
    update();
  }
}
